package com.example.online_order.conrtoller;

import cn.hutool.core.io.FileUtil;
import com.example.online_order.pojo.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@CrossOrigin
@RequestMapping("/files")
public class FileController {

    private  static  final String filePath =System.getProperty("user.dir") + "/files/";

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file){

        if(!FileUtil.exist(filePath)){
            FileUtil.mkdir(filePath);
        }
        String realPath = filePath + file.getOriginalFilename();
        try {
            file.transferTo(new File(realPath));
            String url ="http://localhost:8080/files/download/"+file.getOriginalFilename();
            return new Result(url,"上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败",444);
        }
    }

    @GetMapping("/download/{fileName}")
    public void downloadFile(@PathVariable ("fileName") String fileName, HttpServletResponse response) throws IOException {

        String realpath = filePath + fileName;
        byte[] bytes = FileUtil.readBytes(realpath);
        response.setContentType("application/octet-stream");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
        ServletOutputStream os = response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();

    }
    }
